<?php if (!defined('TL_ROOT')) die('You can not access this file directly!');

/**
 * TYPOlight webCMS
 *
 * The TYPOlight webCMS is an accessible web content management system that 
 * specializes in accessibility and generates W3C-compliant HTML code. It 
 * provides a wide range of functionality to develop professional websites 
 * including a built-in search engine, form generator, file and user manager, 
 * CSS engine, multi-language support and many more. For more information and 
 * additional TYPOlight applications like the TYPOlight MVC Framework please 
 * visit the project website http://www.typolight.org.
 *
 * This is the data container array for table tl_catalog_types.
 *
 * PHP version 5
 * @copyright  Martin Komara, Thyon Design 2008
 * @author     Martin Komara, John Brand <john.brand@thyon.com> 
 * @package    Catalog 
 * @license    GPL 
 * @filesource
 */


/**
 * Table tl_catalog_types 
 */
			
$GLOBALS['TL_DCA']['tl_catalog_types'] = array
(

	// Config
	'config' => array
	(
		'dataContainer'               => 'Table',
		'ctable'                      => array('tl_catalog_fields'),
		'switchToEdit'                => true,
		'enableVersioning'            => true,
		'onload_callback'             => array
			(
				array('tl_catalog_types', 'checkPermission'),
				array('tl_catalog_types', 'checkRemoveTable'),
				array('tl_catalog_types', 'regenerateAllDCA'),
			)
		),

	// List
	'list' => array
	(
		'sorting' => array
		(
			'mode'                    => 1,
			'fields'                  => array('name'),
			'flag'                    => 1,
			'panelLayout'             => 'filter;search,limit'
		),

		'label' => array
		(
			'fields'                  => array('name'),
			'format'                  => '%s',
			'label_callback'		  => array('tl_catalog_types','getRowLabel')
		),

		'global_operations' => array
		(
            
			'regenerateDca' => array
			(
				'label'               => &$GLOBALS['TL_LANG']['tl_catalog_types']['regenerateDca'],
				'href'                => 'key=regenerateDca',
				'class'               => 'navigation settings',
				'attributes'          => 'onclick="Backend.getScrollOffset();"'
			),
            
			'all' => array
			(
				'label'               => &$GLOBALS['TL_LANG']['MSC']['all'],
				'href'                => 'act=select',
				'class'               => 'header_edit_all',
				'attributes'          => 'onclick="Backend.getScrollOffset();"'
			),
		),

		'operations' => array
		(
			'edit' => array
			(
				'label'               => &$GLOBALS['TL_LANG']['tl_catalog_types']['edit'],
				'href'                => 'table=tl_catalog_items',
				'icon'                => 'edit.gif',
			),
			'copy' => array
			(
				'label'               => &$GLOBALS['TL_LANG']['tl_catalog_types']['copy'],
				'href'                => 'act=copy',
				'icon'                => 'copy.gif',
				'button_callback'			=> array('tl_catalog_types', 'copyBtn')
			),
			'delete' => array
			(
				'label'               => &$GLOBALS['TL_LANG']['tl_catalog_types']['delete'],
				'href'                => 'act=delete',
				'icon'                => 'delete.gif',
				'button_callback'			=> array('tl_catalog_types', 'deleteBtn'),
				'attributes'          => 'onclick="if (!confirm(\'' . $GLOBALS['TL_LANG']['MSC']['deleteConfirm'] . '\')) return false; Backend.getScrollOffset();"'

			),
			'show' => array
			(
				'label'               => &$GLOBALS['TL_LANG']['tl_catalog_types']['show'],
				'href'                => 'act=show',
				'icon'                => 'show.gif'
			),
      'fields' => array
			(
				'label'               => &$GLOBALS['TL_LANG']['tl_catalog_types']['fields'],
				'href'                => 'table=tl_catalog_fields',
				'icon'                => 'tablewizard.gif',
        'button_callback'     => array('tl_catalog_types', 'fieldsButton')
			)
		)
	),

	// Palettes
	'palettes' => array
	(
		'__selector__'            => array('addImage'),
		'default'                 => 'name,tableName;addImage;format',
	),

	// Subpalettes
	'subpalettes' => array
	(
		'addImage'                 => 'singleSRC,size',
	),


	// Fields
	'fields' => array
	(
		'name' => array
		(
			'label'                   => &$GLOBALS['TL_LANG']['tl_catalog_types']['name'],
			'exclude'                 => true,
			'inputType'               => 'text',
			'eval'                    => array('mandatory'=>true, 'maxlength'=>255)
		),
        
		'tableName' => array
		(
			'label'                   => &$GLOBALS['TL_LANG']['tl_catalog_types']['tableName'],
			'exclude'                 => true,
			'inputType'               => 'text',
			'eval'                    => array('mandatory'=>true, 'maxlength'=>64, 'doNotCopy'=>true),
			'save_callback'           => array
			(
				array('Catalog', 'renameTable')
			)
		),
        
		'noTable' => array
		(
			'label'                   => &$GLOBALS['TL_LANG']['tl_catalog_types']['noTable'],
			'exclude'                 => true,
			'inputType'               => 'checkbox',
		),
	
	// added by thyon
		'addImage' => array
		(
			'label'                   => &$GLOBALS['TL_LANG']['tl_catalog_types']['addImage'],
			'exclude'                 => true,
			'inputType'               => 'checkbox',
			'eval'                    => array('submitOnChange'=>true)
		),
		'singleSRC' => array
		(
			'label'                   => &$GLOBALS['TL_LANG']['tl_catalog_types']['singleSRC'],
			'exclude'                 => true,
			'inputType'               => 'fileTree',
			'eval'                    => array('fieldType'=>'radio', 'files'=>true, 'filesOnly'=>true, 'mandatory'=>true, 'extensions' => 'jpg,jpeg,gif,png,tif,tiff')
		),
		'size' => array
		(
			'label'                   => &$GLOBALS['TL_LANG']['tl_catalog_types']['size'],
			'exclude'                 => true,
			'inputType'               => 'text',
			'eval'                    => array('multiple'=>true, 'size'=>2, 'rgxp'=>'digit', 'nospace'=>true)
		),

		'format' => array
		(
			'label'                   => &$GLOBALS['TL_LANG']['tl_catalog_types']['format'],
			'exclude'                 => true,
			'search'                  => true,
			'inputType'               => 'textarea',
			'eval'                    => array('allowHtml'=>true)
		),

	)
);

class tl_catalog_types extends Backend
{

	/**
	 * Check permissions to edit table tl_catalog_types
	 */
	public function checkPermission()
	{
		$this->import('BackendUser', 'User');


		if ($this->User->isAdmin)
		{
			return;
		}

		// Set root IDs
		if (!is_array($this->User->catalogs) || count($this->User->catalogs) < 1)
		{
			$root = array(0);
		}
		else
		{
			$root = $this->User->catalogs;
		}

		$GLOBALS['TL_DCA']['tl_catalog_types']['config']['closed'] = true;
		$GLOBALS['TL_DCA']['tl_catalog_types']['list']['sorting']['root'] = $root;

		// Check current action
		switch ($this->Input->get('act'))
		{
			case 'select':
				// Allow
				break;

			case 'edit':
			case 'show':
				if (!in_array($this->Input->get('id'), $root))
				{
					$this->log('Not enough permissions to '.$this->Input->get('act').' catalog type ID "'.$this->Input->get('id').'"', 'tl_catalog_types checkPermission', 5);
					$this->redirect('typolight/main.php?act=error');
				}
				break;

			case 'editAll':
				$session = $this->Session->getData();
				$session['CURRENT']['IDS'] = array_intersect($session['CURRENT']['IDS'], $root);
				$this->Session->setData($session);
				break;

			default:
				if (strlen($this->Input->get('act')))
				{
					$this->log('Not enough permissions to '.$this->Input->get('act').' catalog types', 'tl_catalog_types checkPermission', 5);
					$this->redirect('typolight/main.php?act=error');
				}
				break;
		}
	}



  public function getRowLabel($row, $label, $dc)
  {
		// add image
		$image = '';
		if ($row['addImage'])
		{
			$size = deserialize($row['size']);
			$image = '<div class="image" style="padding-top:3px"><img src="'.$this->getImage($row['singleSRC'], $size[0], $size[1]).'" alt="'.htmlspecialchars($label).'" /></div> ';
 		}
  
		// count items
		$objCount = $this->Database->prepare("SELECT count(*) AS itemCount FROM ".$row['tableName'])
					->execute();
		$itemCount =  sprintf($GLOBALS['TL_LANG']['tl_catalog_types']['itemFormat'], $objCount->itemCount, ($objCount->itemCount == 1) ? sprintf($GLOBALS['TL_LANG']['tl_catalog_types']['itemSingle']) : sprintf($GLOBALS['TL_LANG']['tl_catalog_types']['itemPlural']));
		  
  	return '<span class="name">'.$label. $itemCount . '</span>'.$image;
  }

	/**
	 * Return the copy archive button
	 * @param array
	 * @param string
	 * @param string
	 * @param string
	 * @param string
	 * @param string
	 * @return string
	 */
	public function copyBtn($row, $href, $label, $title, $icon, $attributes)
	{
		if (!$this->User->isAdmin)
		{
			return '';
		}

		return '<a href="'.$this->addToUrl($href.'&amp;id='.$row['id']).'" title="'.specialchars($title).'"'.$attributes.'>'.$this->generateImage($icon, $label).'</a> ';
	}


	/**
	 * Return the delete archive button
	 * @param array
	 * @param string
	 * @param string
	 * @param string
	 * @param string
	 * @param string
	 * @return string
	 */
	public function deleteBtn($row, $href, $label, $title, $icon, $attributes)
	{
		if (!$this->User->isAdmin)
		{
			return '';
		}

		return '<a href="'.$this->addToUrl($href.'&amp;id='.$row['id']).'" title="'.specialchars($title).'"'.$attributes.'>'.$this->generateImage($icon, $label).'</a> ';
	}
	
	public function editItem($row, $href, $label, $title, $icon, $attributes)
	{
		return '<a href="'.$this->addToUrl('table=tl_catalog_items&amp;id='.$row['id']).'" title="'.specialchars($title).'"'.$attributes.'>'.$this->generateImage($icon, $label).'</a>  ';
	}

	public function fieldsButton($row, $href, $label, $title, $icon, $attributes)
	{
		$this->import('BackendUser', 'User');
	
		if (!$this->User->isAdmin)
		{
			return '';
		}
	
		return '<a href="'.$this->addToUrl($href.'&amp;id='.$row['id']).'" title="'.specialchars($title).'"'.$attributes.'>'.$this->generateImage($icon, $label).'</a> ';
	} 


 
    
	public function checkRemoveTable(DataContainer $dc)
	{
		$act = $this->Input->get('act');
		if ($act == 'deleteAll' || $act == 'delete')
		{
			if ($act == 'delete')
			{
				$ids = array($dc->id);
			} 
			else
			{
				$session = $this->Session->getData();
				$ids = $session['CURRENT']['IDS']; 
			}
			
			$objType = $this->Database->execute(
					sprintf("SELECT tableName, noTable FROM tl_catalog_types WHERE id IN (%s) AND noTable=''",
							implode(',', $ids)));
					
			while ($objType->next())
			{
				$tableName = $objType->tableName;
				
				if ($this->Database->tableExists($tableName))
				{
					$this->import('Catalog');
					$this->Catalog->dropTable($tableName);
				}
			}
		}
	}
   

	public function regenerateAllDCA(DataContainer $dc)
	{
		$this->import('Catalog');

		$objTypes = $this->Database->execute("SELECT * FROM tl_catalog_types");
		while ($objTypes->next())
		{
			$this->Catalog->regenerateDca($objTypes->id);
		}
	}


}

?>